package pers.xhh.shopapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.dao.MiCategoryDao;
import pers.xhh.shopapi.entity.MiCategoryEntity;
import pers.xhh.shopapi.entity.to.category.MiCategoryNameTo;
import pers.xhh.shopapi.entity.to.category.MiCategoryTo;
import pers.xhh.shopapi.entity.vo.category.MiCategoryVo;
import pers.xhh.shopapi.service.MiCategoryService;
import pers.xhh.shopapi.service.MiGoodsService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wei-xhh
 * @date 2020-11-22
 */
@Service
public class MiCategoryServiceImpl extends ServiceImpl<MiCategoryDao, MiCategoryEntity> implements MiCategoryService {

    @Autowired
    MiGoodsService miGoodsService;

    @Override
    public Mi listCategory(Integer type, Integer pagenum, Integer pagesize) {
        // ->如果pagenum和pagesize有一个为空,不分页
        if (pagenum == null || pagesize == null) {
            if(type != null){
                // 如果type为1
                if (type == 1) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
                if (type == 2) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
                if (type == 3) {
                    List<MiCategoryVo> collect = getMiCategoryByType(type);
                    return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
                }
            }
        }
        // ->分页条件都不为空
        if (pagenum != null && pagesize != null) {
            // 分页条件不为空,由于children的限制,只能查询出全部在分页,否则children也
            // TODO 后期可优化
            List<MiCategoryVo> collect = getMiCategoryByType(3);
            // 先对cat_level进行分页
            List<MiCategoryVo> list = new ArrayList<>();
            int total = collect.size();
            // 从哪开始
            int start = (pagenum - 1) * pagesize;
            // 截多少 pagesize
            int j = 0;
            for (int i = start; i < collect.size(); i++) {
                j++;
                list.add(collect.get(i));
                if(j == pagesize){
                    break;
                }
            }

            Map<String, Object> map = new HashMap<>();
            map.put("result", list);
            map.put("total", total);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }

        // ->默认全部,参数给错也一样
        List<MiCategoryVo> collect = getMiCategoryByType(3);
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);

    }

    @Override
    public Mi saveCategory(MiCategoryTo miCategoryTo) {
        Integer catPid = Integer.parseInt(miCategoryTo.getCat_pid());
        String catName = miCategoryTo.getCat_name();
        Integer catLevel = miCategoryTo.getCat_level();
        MiCategoryEntity miCategoryEntity = new MiCategoryEntity();
        miCategoryEntity.setCatPid(catPid);
        miCategoryEntity.setCatName(catName);
        miCategoryEntity.setCatLevel(catLevel);
        miCategoryEntity.setUpdateTime(new Date());
        miCategoryEntity.setCreateTime(new Date());

        boolean save = this.save(miCategoryEntity);
        if (save) {
            Map<String, Object> map = new HashMap<>();
            map.put("cat_id", catPid);
            map.put("cat_name", catName);
            map.put("cat_level", catLevel);
            return Mi.ok(ResultCode.SUCCESS1.getMessage(), ResultCode.SUCCESS1.getStatus(), map);
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi getCategoryById(Integer id) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        MiCategoryEntity byId = this.getById(id);
        if(byId != null){
            Map<String, Object> map = new HashMap<>();
            map.put("cat_id", byId.getCatId());
            map.put("cat_name", byId.getCatName());
            map.put("cat_level", byId.getCatLevel());
            map.put("cat_pid", byId.getCatPid());
            map.put("cat_deleted", byId.getCatDeleted() == 1);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }

        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi updateCatName(Integer id, MiCategoryNameTo miCategoryNameTo) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }

        String catName = miCategoryNameTo.getCat_name();
        MiCategoryEntity categoryEntity = new MiCategoryEntity();
        categoryEntity.setCatId(id);
        categoryEntity.setCatName(catName);
        categoryEntity.setUpdateTime(new Date());

        boolean b = this.updateById(categoryEntity);
        if(b){
            Map<String, Object> map = new HashMap<>();
            map.put("cat_id", id);
            map.put("cat_name", catName);

            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi deleteCat(Integer id) {
        if(id == null || id <= 0){
            return Mi.error(ResultCode.ERROR308.getMessage(), ResultCode.ERROR308.getStatus());
        }
        // TODO 修改为逻辑删除 cat_deleted：0未删除;1删除
        boolean b = this.removeById(id);
        if(b){
            Map<String, Object> map = new HashMap<>();
            map.put("cat_id", id);
            return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), map);
        }
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }

    @Override
    public Mi getCateOneList() {
        List<MiCategoryEntity> categoryEntities = this.list(new QueryWrapper<MiCategoryEntity>().eq("cat_pid", 0));
        List<Map<String, Object>> collect = categoryEntities.stream().map(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("catOneId", item.getCatId());
            map.put("catOneName", item.getCatName());
            return map;
        }).collect(Collectors.toList());
        return Mi.ok(ResultCode.SUCCESS.getMessage(), ResultCode.SUCCESS.getStatus(), collect);
    }

    private List<MiCategoryVo> getMiCategoryByPage(Integer type, Integer pagenum, Integer pagesize) {
        // TODO 分页有点问题,当pagenum,pagesize,type 暂时不解决
        System.out.println("开始分页");
        Page<MiCategoryEntity> page = new Page<>(pagenum, pagesize);
//        QueryWrapper<MiCategoryEntity> queryWrapper = new QueryWrapper<>();
//        if (type == null) {
//            type = 3;
//        }
//        if (type == 1) {
//            queryWrapper =
//                    new QueryWrapper<MiCategoryEntity>().eq("cat_level", type - 1);
//        }
//        if (type == 2) {
//            queryWrapper =
//                    new QueryWrapper<MiCategoryEntity>()
//                            .eq("cat_level", type - 2)
//                            .or()
//                            .eq("cat_level", type - 1);
//        }
//        if (type == 3) {
//            queryWrapper = new QueryWrapper<MiCategoryEntity>().eq("cat_level", 0);
//        }
        this.page(page, new QueryWrapper<>());
        List<MiCategoryEntity> records = page.getRecords();

        List<MiCategoryVo> miCategoryVos = records.stream().map(item -> {
            MiCategoryVo miCategoryVo = new MiCategoryVo();
            miCategoryVo.setCat_id(item.getCatId());
            miCategoryVo.setCat_name(item.getCatName());
            miCategoryVo.setCat_pid(item.getCatPid());
            miCategoryVo.setCat_level(item.getCatLevel());
            miCategoryVo.setCat_deleted(item.getCatDeleted() == 1);
            return miCategoryVo;
        }).collect(Collectors.toList());
        // 找到一级菜单,递归查询
        return miCategoryVos.stream().filter(miCategoryVo ->
                miCategoryVo.getCat_level() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, miCategoryVos, type));
            return menu;
        }).collect(Collectors.toList());
    }

    private List<MiCategoryVo> getMiCategoryByType(Integer type) {
        QueryWrapper<MiCategoryEntity> queryWrapper = new QueryWrapper<>();
        if (type == 1) {
            queryWrapper =
                    new QueryWrapper<MiCategoryEntity>().eq("cat_level", type - 1);
        }
        if (type == 2) {
            queryWrapper =
                    new QueryWrapper<MiCategoryEntity>()
                            .eq("cat_level", type - 2)
                            .or()
                            .eq("cat_level", type - 1);
        }
        if (type == 3) {
            queryWrapper = new QueryWrapper<>();
        }
        // TODO 修改为逻辑删除 cat_deleted：0未删除;1删除 添加这个条件
        List<MiCategoryEntity> catLevel = this.list(queryWrapper);
        List<MiCategoryVo> miCategoryVos = catLevel.stream().map(item -> {
            MiCategoryVo miCategoryVo = new MiCategoryVo();
            miCategoryVo.setCat_id(item.getCatId());
            miCategoryVo.setCat_name(item.getCatName());
            miCategoryVo.setCat_pid(item.getCatPid());
            miCategoryVo.setCat_level(item.getCatLevel());
            miCategoryVo.setCat_deleted(item.getCatDeleted() == 1);
            return miCategoryVo;
        }).collect(Collectors.toList());

        // 找到一级菜单,递归查询
        return miCategoryVos.stream().filter(miCategoryVo ->
                miCategoryVo.getCat_level() == 0
        ).map((menu) -> {
            menu.setChildren(getChildren(menu, miCategoryVos, type));
            return menu;
        }).collect(Collectors.toList());
    }

    // 找到一级菜单下的子菜单,递归查找菜单的所有子菜单
    private List<MiCategoryVo> getChildren(MiCategoryVo root, List<MiCategoryVo> all, Integer type) {
        List<MiCategoryVo> collect = all.stream().filter(categoryVo ->
                categoryVo.getCat_pid().equals(root.getCat_id())
        )
                .map((menu) -> {
                    // 找到子菜单
                    if(type == 2){
                        if(menu.getCat_level() <= 0){
                            menu.setChildren(getChildren(menu, all, type));
                        }
                    } else {
                        if(menu.getCat_level() <= 1){
                            menu.setChildren(getChildren(menu, all, type));
                        }
                    }
                    return menu;
                }).collect(Collectors.toList());

        return collect;
    }

}
